package _01_第一季.链表02;

import _01_第一季._00_公共接口.AbstractList;
/*
    单向链表
 */
public class LinkedSingleList<E> extends AbstractList<E>{
    private Node<E> first;

    private static class Node<E>{
        E element;
        Node<E> next;
        public Node(){
            this(null,null);
        }
        public Node(E element,Node<E> next){
            this.element = element;
            this.next = next;
        }
    }

    private Node<E> node(int index){
        rangeCheck(index);
        Node<E> node = first;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        if(index == 0){
            first = new Node<>(element,first);
        }else{
            Node<E> prev = node(index - 1);
            prev.next = new Node<>(element,prev.next);
        }
        size++;
    }

    @Override
    public void remove(E element) {
        int index = indexOf(element);
        if(index!=ELEMENT_NOT_FOUND){
            remove(index);
        }else{
            throw new IllegalArgumentException("element not found");
        }
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);
        Node<E> node = first;

        if(index == 0){
            first = first.next;
        }else{
            Node<E> prev = node(index-1);
            node = prev.next;
            prev.next = node.next;
        }
        size--;
        return node.element;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = node(index);
        E ret = node.element;
        node.element = element;
        return ret;
    }

    @Override
    public int indexOf(E element) {
        if(element == null){
            Node<E> node= first;
            for(int i=0;i<size;++i){
                if(node.element==null) return i;
                node = node.next;
            }
        }else{
            Node<E> node = first;
            for(int i=0;i<size;++i){
                if(element.equals(node.element)) return i;
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(String.format("LinkedSinglyList:%d [",size)); //只有元素个数
        if(isEmpty()){
            sb.append(']');
        }else {
            Node<E> p =first; //代替头指针去遍历链表
            while(true){
                sb.append(p.element); //拼接数据
                if(p.next==null){ //如果到达了最后一个结点
                    sb.append(']');
                    break;
                }
                //不是最后一个结点，就拼接,号，并向后移
                sb.append(',');
                p=p.next;
            }
        }
        return sb.toString();
    }
}
